<?php

//
///*
// * To change this template, choose Tools | Templates
// * and open the template in the editor.
// */
$categoryFile = "category.csv";
$categoryArray = file($categoryFile);
$dbhost = "localhost";
$username = "root";
$password = "freemysql";
$dbname = "eclass";
$mysqli = new mysqli($dbhost, $username, $password, $dbname);
$mysqli->query("SET NAMES UTF8");
//$testSql = "select * from admin";
////
//$resultSet= $mysqli->query($testSql);
//while($row = $resultSet->fetch_row()){
//    print_r($row);
//}
//exit;
//
//

foreach ($categoryArray as $categoryLine) {
    $categoryLineArray = split(",", $categoryLine);
    $level1 = $categoryLineArray[0];
    $level2 = $categoryLineArray[1];
    $level3 = $categoryLineArray[2];

    if ($level1) {
        $category = removeNL($level1);
        $parentId = 0;
        //do the insert sql
        $sql = getSql($category, $parentId) . "\n";
        echo $sql;
        $mysqli->query($sql);
        $level1Id = $mysqli->insert_id;
    }

    if ($level2) {
        $category = removeNL($level2);
        $parentId = $level1Id;
        $sql = getSql($category, $parentId) . "\n";
        echo $sql;
        $mysqli->query($sql);
        $level2Id = $mysqli->insert_id;
    }

    $category = removeNL($level3);
    $parentId = $level2Id;
    echo $sql;
    $sql = getSql($category, $parentId) . "\n";
    $mysqli->query($sql);
}

function getSql($level, $parentId) {
    $sql = "insert into category (`name`,`parent-id`,`description`) values ('" . $level . "'," . $parentId . "," . "'" . $level . "');";
    return $sql;
}

function removeNL($level) {
    $splitted = split("\n", $level);
    return $splitted[0];
}

?>
